<template>
  <el-container>
    <el-dialog
      :title="isAdd ? '企业添加' : '企业编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="30%"
      center
    >
      <el-form
        ref="companyForm"
        :model="companyForm"
        label-width="100px"
        fullscreenLoading
        :rules="companyFormRules"
      >
        <el-form-item label="企业名称" :prop="isAdd ? 'name' : 'editName'">
          <el-input
            v-model="companyForm.name"
            placeholder="请输入企业名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="企业编码" prop="code">
          <el-input
            v-model="companyForm.code"
            placeholder="请输入企业编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="企业描述" prop="description">
          <el-input
            v-model="companyForm.description"
            placeholder="请输入企业描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系热线" prop="phone">
          <el-input
            v-model="companyForm.phone"
            placeholder="请输入联系热线"
          ></el-input>
        </el-form-item>
        <el-form-item label="企业地址" prop="address">
          <el-input
            v-model="companyForm.address"
            placeholder="请输入企业地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="企业邮箱" prop="mail">
          <el-input
            v-model="companyForm.mail"
            placeholder="请输入企业邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('companyForm')"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确认</el-button
          >
          <el-button @click="resetForm('companyForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增按钮</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="请输入企业名称"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="companyName"
          >
          </el-input>
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="请输入企业编码"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="companyCode"
          >
          </el-input>
          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="companyTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="companys"
            fit
            max-height="700"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="企业描述">
                    <span>{{ props.row.description }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="name" label="企业名称"> </el-table-column>
            <el-table-column prop="code" label="企业编号"> </el-table-column>
            <el-table-column prop="phone" label="企业联系电话">
            </el-table-column>
            <el-table-column prop="mail" label="企业邮箱"> </el-table-column>
            <el-table-column prop="address" label="企业地址"> </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
export default {
  name: 'CompanyMng',
  data() {
    let validateCodeIsRepeat = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('请输入专业名称')]);
      }
      console.log(value);
      if (this.isAdd) {
        // 检查是否重名
        let result = await this.$store.dispatch(
          'CompanyMng/checkIsRepeatForCompanyCode',
          value
        );
        return result.data.flag
          ? callback()
          : callback([new Error(result.message)]);
      }
    };
    return {
      companys: [], // 展示企业列表
      total: 0, // 总记录数
      currentPage: 1, // 当前页
      pageSize: 10, // 每页显示条数
      loading: false, // 遮罩层
      condition: {}, // 查询条件封装对象
      isAdd: false, // 增加操作标志符
      fullscreenLoading: false,
      companyForm: {}, // 表单对象
      centerDialogVisible: false, // 对话框开关
      companyName: '', // 搜索框 公司名称
      companyCode: '', // 搜索框  公司s编码
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true, // 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
      },
      companyFormRules: {
        // 校验规则
        name: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' },
        ],
        code: [
          { required: true, validator: validateCodeIsRepeat, trigger: 'blur' },
        ],
        address: [
          { required: true, message: '企业地址不能为空', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '企业电话不能为空', trigger: 'blur' },
        ],
        mail: [
          { required: true, message: '企业邮箱不能为空', trigger: 'blur' },
          // {
          //   pattern:
          //     /^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$/,
          //   message: '邮箱不合法!',
          // },
        ],
      },
    };
  },
  computed: {
    ...mapGetters('CompanyMng', ['companyIPage', 'companyList']),
  },
  watch: {
    companyIPage() {
      this.loading = false;
      this.$set(this, 'total', this.companyIPage.total);
      this.currentPage = this.companyIPage.currentPage;
      this.pageSize = this.companyIPage.pageSize;
    },
    companyList() {
      this.$set(this, 'companys', this.companyList);
    },
    isAdd() {
      // 将isAdd变量赋值window对象
      window.isAdd = this.isAdd;
    },
  },
  mounted() {
    // 获取初始化数据
    this.getCompanyList();
  },
  methods: {
    // 删除企业
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('CompanyMng/delCompany', [
            row.id,
          ]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
        });
    },

    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },
    // 编辑企业
    handEdit(row) {
      if (this.$refs.companyForm) {
        this.resetForm('companyForm');
      }
      let temp = {
        ...row,
      };
      this.companyForm = temp;
      this.centerDialogVisible = true;
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCompanyList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getCompanyList();
    },
    // 条件查询
    async queryByCondition() {
      // 初始化条件查询参数
      this.condition = {};
      if (this.companyName) {
        this.condition.name = this.companyName;
      }
      if (this.companyCode) {
        this.condition.code = this.companyCode;
      }
      await this.getCompanyList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },

    // 刷新企业列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getCompanyList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),
    // 新增企业
    handleAdd() {
      this.companyForm = {};
      if (this.$refs.companyForm) {
        this.resetForm('companyForm');
      }
      this.isAdd = true;
      this.centerDialogVisible = true;
    },

    // 级联选择器
    cascaderChange() {
      // this.$refs["departmentAndMajor"].getCheckedNodes()//完整的数据
      //this.$refs["departmentAndMajor"].getCheckedNodes()[0].pathLabels//value的值
    },

    // 获取企业列表
    getCompanyList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition,
      };
      this.$store.dispatch('CompanyMng/getCompanyList', params);
    },

    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            let result = {};
            if (this.isAdd) {
              let paramsArray = [];
              // 发送请求
              let params = {
                ...this.companyForm,
              };
              paramsArray.push(params);
              result = await this.$store.dispatch(
                'CompanyMng/batchAddCompany',
                paramsArray
              );
            } else {
              result = await this.$store.dispatch(
                'CompanyMng/editCompany',
                this.companyForm
              );
            }
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
            // 更新企业列表
            this.getCompanyList();
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            this.fullscreenLoading = false;
            this.isAdd = false;
            this.centerDialogVisible = false;
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
/* 表格扩展样式 */
// 表格扩展样式
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.function-button {
  margin-bottom: 10px;
}

.tableStyle {
  // height: $tableHeight;
}

// 分页插件居中对齐
.block {
  text-align: center;
}
</style>
